from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from app01.tool import TokenFun
from app01 import models
from app01.tool import auth_token, get_code
from app01 import ser

import datetime


class User(APIView):
    def get(self, request):
        # 登录
        dic = {'code': 200, 'msg': 'ok'}
        try:
            print(request.query_params)
            username = request.query_params.get('username')
            password = request.query_params.get('password')
            # print(request.META.get('HTTP_TOKEN'))
            user_obj = models.Users.objects.filter(username=username)
            if user_obj:
                user_obj = user_obj.filter(password=password)
                if user_obj:
                    dic['code'] = 100
                    dic['msg'] = '登录成功'
                    user_obj.update(is_login=1)
                    token = TokenFun(user_obj[0])
                    data = token.login()
                    dic['token'] = data
                    return Response(dic)
                dic['msg'] = '密码错误'
            else:
                dic['msg'] = '账号不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    def post(self, request):
        # 注册
        dic = {'code': 100, 'msg': 'ok'}
        try:
            user_ser = ser.UserSer(data=request.data)
            if user_ser.is_valid():
                user_ser.save()
            else:
                dic['code'] = 200
                dic['msg'] = list(user_ser.errors.values())[0][0]
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


# 删除了re_password

class Lease(APIView):
    # 出租人
    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        data = request.data
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        try:
            space_obj = ser.ParkingSpaceSer(data=data)
            if not space_obj.is_valid():
                dic['code'] = 200
                dic['msg'] = list(space_obj.errors.values())[0][0]
                return Response(dic)
            time_list = data.get('period')
            if not isinstance(time_list, list):
                dic['code'] = 200
                dic['msg'] = '发送类型不对，应该为包含键值对的列表'
                return Response(dic)
            if len(time_list) == 0:
                dic['code'] = 200
                dic['msg'] = '时间列表不能为空'
                return Response(dic)
            print(data.get('device_id'))
            device_obj = models.UserDevice.objects.filter(number=data.get('device_id'))
            if not device_obj:
                dic['code'] = 200
                dic['msg'] = '编号' + data.get('device_id') + '的设备不存在'
                return Response(dic)
            device_obj.update(is_use=1)
            obj = models.ParkingSpace.objects.create(address=data.get('address'),
                                                     device=device_obj.first(),
                                                     longitude=str(data.get('longitude')),
                                                     latitude=str(data.get('latitude')),
                                                     user=user)
            for i in time_list:
                time_obj = ser.PeriodSer(data=i)
                if time_obj.is_valid():
                    i['parking_space'] = obj
                    models.ParkingPeriod.objects.create(**i)
                else:
                    dic['code'] = 200
                    obj.delete()
                    print(time_obj.errors)
                    dic['msg'] = list(time_obj.errors.values())[0][0]
                    return Response(dic)
            dic['msg'] = '共享车位创建成功'
            dic['data'] = {'order_id': obj.pk}
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def delete(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            space_id = int(request.POST.get('id'))
            if models.ParkingSpace.objects.filter(id=space_id):
                models.ParkingPeriod.objects.filter(id=space_id).delete()
            else:
                dic['code'] = 200
                dic['msg'] = '该出租车位不存在'
                return Response(dic)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        dic['msg'] = '该出租车位已删除'
        return Response(dic)

    @auth_token
    def put(self, request):
        # 修改信息
        pass


class Rent(APIView):
    # 租车人

    @auth_token
    def get(self, request):
        # 查看可出租信息
        dic = {'code': 100, 'msg': 'ok'}
        try:
            address = request.query_params.get('address')
            data = models.ParkingSpace.objects.filter(address__contains=address)
            park_ser = ser.ParkingSpaceSer(instance=data, many=True)
            dic['data'] = park_ser.data
            for i in range(len(dic['data'])):
                period_obj = models.ParkingPeriod.objects.filter(parking_space_id=dic['data'][i]['id'])
                period_ser = ser.PeriodSer(period_obj, many=True)
                dic['data'][i]['period'] = period_ser.data
            return Response(dic)
        except Exception as e:
            dic['code'] = 200
            print(e)
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def post(self, request):
        # 租用
        dic = {'code': 100, 'msg': 'ok'}
        user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
        try:
            car = request.POST.get('car')
            space_id = int(request.POST.get('id'))
            start_time = request.POST.get('start_time')
            end_time = request.POST.get('end_time')
            if models.Orders.objects.filter(car=car, status=0):
                dic['code'] = 200
                dic['msg'] = '该车牌号已有车位预定，不可重复预定'
                return Response(dic)
            if models.Orders.objects.filter(parking_space_id=space_id, status=0):
                dic['code'] = 200
                dic['msg'] = '该车位已被预定，请选择其他车位'
                return Response(dic)
            if not models.ParkingSpace.objects.filter(id=space_id):
                dic['code'] = 200
                dic['msg'] = '该车位不存在或已被删除，请咨询客服'
                return Response(dic)
            code = get_code('1')
            code_obj = models.Code.objects.create(code=code)
            obj = models.Orders.objects.create(user=user, car=car,
                                               parking_space_id=space_id, code=code_obj,
                                               start_time=start_time, end_time=end_time)
            dic['msg'] = '订单创建完成'
            dic['data'] = {'order_id': obj.id}
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def delete(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            order_id = int(request.POST.get('id'))
            if models.Orders.objects.filter(id=order_id, status=0):
                models.Orders.objects.filter(id=order_id).update(status=1)
            else:
                dic['code'] = 200
                dic['msg'] = '该订单不存在'
                return Response(dic)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        dic['msg'] = '订单已完成'
        return Response(dic)


class CodeNumber(APIView):

    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            order_id = request.query_params.get('id')
            if models.Orders.objects.filter(id=order_id, status=0):
                code_obj = models.Code.objects.filter(orders__id=order_id).first()
                end_time = code_obj.create_time + datetime.timedelta(minutes=10)
                end_time = end_time.replace(tzinfo=None)
                print(end_time)
                if datetime.datetime.now() < end_time:
                    dic['data'] = {'code': code_obj.token, 'tip': '二维码尚未过期'}
                else:
                    new_code = get_code(order_id)
                    models.Code.objects.filter(orders__id=order_id).update(code=new_code, create_time=datetime.datetime.now())
                    dic['data'] = {'code': new_code, 'tip': '二维码已更新'}
            else:
                dic['code'] = 200
                dic['msg'] = '订单不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)

        return Response(dic)

    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            order_id = request.data.get('id')
            if models.Orders.objects.filter(id=order_id, status=0):
                new_code = get_code(order_id)
                models.Code.objects.filter(orders__id=order_id).update(code=new_code,
                                                                       create_time=datetime.datetime.now())
                dic['data'] = {'code': new_code, 'tip': '二维码已更新'}
            else:
                dic['code'] = 200
                dic['msg'] = '订单不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)

        return Response(dic)


class Device(APIView):
    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            device_obj = models.UserDevice.objects.filter(user__token__token=request.META.get('HTTP_TOKEN'))
            print(device_obj)
            device_ser = ser.DeviceSer(device_obj, many=True)
            dic['data'] = device_ser.data
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            device_name = request.data.get('device_name')
            device_number = request.data.get('device_number')
            print(device_number)
            if len(device_name) == 0 or len(device_number) == 0:
                dic['code'] = 200
                dic['msg'] = '设备名或设备编号不能为空'
                return Response(dic)
            user_obj = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
            device_name_obj = models.Device.objects.filter(name=device_name).first()
            if device_name_obj:
                models.UserDevice.objects.create(number=device_number, device=device_name_obj,
                                                 user=user_obj)
            else:
                dic['code'] = 200
                dic['msg'] = '该型号不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def delete(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            device_number = request.data.get('device_number')
            device_obj = models.UserDevice.objects.filter(number=device_number,
                                                          user__token__token=request.META.get('HTTP_TOKEN'))
            if device_obj:
                device_obj.delete()
            else:
                dic['code'] = 200
                dic['msg'] = '该设备不存在'
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class DeviceType(APIView):
    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            device_type_obj = models.Device.objects.all()
            device_type_ser = ser.DeviceNameSer(device_type_obj, many=True)
            dic['data'] = device_type_ser.data
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class Order(APIView):
    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            order_obj = models.Orders.objects.filter(user__token__token=request.META.get('HTTP_TOKEN'))
            order_ser = ser.OrderSer(order_obj, many=True)
            dic['data'] = order_ser.data
            return Response(dic)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)

    @auth_token
    def post(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            order_id = request.data.get('id')
            order_obj = models.Orders.objects.filter(user__token__token=request.META.get('HTTP_TOKEN'),
                                                     pk=order_id
                                                     ).first()
            order_ser = ser.OrderSer(order_obj)
            dic['data'] = order_ser.data
            return Response(dic)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)


class GetUser(APIView):
    @auth_token
    def get(self, request):
        dic = {'code': 100, 'msg': 'ok'}
        try:
            user = models.Users.objects.filter(token__token=request.META.get('HTTP_TOKEN')).first()
            parking_obj = models.ParkingSpace.objects.filter(user=user)
            orders = models.Orders.objects.filter(user=user)
            user_ser = ser.UserInfo(user)
            parking_ser = ser.ParkingSpaceSer(parking_obj, many=True)
            orders_ser = ser.OrderSer(orders, many=True)
            dic['data'] = user_ser.data
            dic['data']['parking_space'] = parking_ser.data
            dic['data']['orders'] = orders_ser.data
            return Response(dic)
        except Exception as e:
            dic['code'] = 200
            dic['msg'] = str(e)
        return Response(dic)




